<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小西瓜 <751707632@qq.com.com>
// +----------------------------------------------------------------------
namespace app\api\model;

use app\admin\model\RouteModel;
use think\Model;
use think\Db;
use app\fowl\model\ImsMeetingJoinModel;
use app\api\model\ImsJoinLogModel;

class ImsStramingLiveModel extends Model
{
    /**
     * 培训数据添加
     * @param array $data  存储数据
     * @return array
     */
    public function set($data)
    {
    	if ( empty($data) ) {
            return ['code'=>'0', 'msg'=>'缺少参数'];
        }
        $data_new = array();
        if(isset($data['user_id']))         $data_new['user_id']        = $data['user_id'];
        if(isset($data['vm_title']))        $data_new['vm_title']       = $data['vm_title'];
        if(isset($data['type_id']))         $data_new['type_id']        = $data['type_id'];
        if(isset($data['start_time']))      $data_new['start_time']     = $data['start_time'];
        if(isset($data['duration']))        $data_new['duration']       = $data['duration'];
        if(isset($data['cover_pic']))       $data_new['cover_pic']      = $data['cover_pic'];
        if(isset($data['intro']))           $data_new['intro']          = $data['intro'];
        if(isset($data['control']))         $data_new['control']        = $data['control'];
        if(isset($data['challenge_id']))    $data_new['challenge_id']   = $data['challenge_id'];
        if(isset($data['challenge_name']))  $data_new['challenge_name'] = $data['challenge_name'];
        if(isset($data['join_way']))        $data_new['join_way']       = $data['join_way'];
        if(isset($data['join_address_id']))  $data_new['join_address_id'] = $data['join_address_id'];
        if(isset($data['status']))          $data_new['status']         = $data['status'];
        // 判断是增加还是修改
        if(!empty($data['id']) && ($id = intval(trim($data['id'])))) {
            $data_new['update_time'] = date('Y-m-d H:i:s', time());
            $this->where('id', $id)->update($data_new);
            return ['code'=>'1', 'msg'=>'修改成功'];
        } else {
            $data_new['create_time'] = date('Y-m-d H:i:s', time());
            $id = $this->insertGetId($data_new);

            // 添加培训限制人员数据
            if ($id && isset($data['restricted'])) {
                foreach ( $data['restricted'] as $v ) {
                    $restricted['vm_id'] = $id;
                    if(isset($v['restricted_id']) && !empty($v['restricted_id'])) {
                        $restricted['restricted_id'] = $v['restricted_id'];
                        if($data['control'] == 2) {
                            $restricted['rule'] = 1;
                        } else {
                            $restricted['rule'] = 2;
                        }
                        Db::name('ims_straming_restricted')->insert($restricted);
                    }  
                }
            }

            // 添加必须参加人员
            if ($id && isset($data['join'])) {
                foreach ( $data['join'] as $v ) {
                    $join['vm_id'] = $id;
                    if(isset($v['join_id']))   $join['join_id'] = $v['join_id'];
                    $join['is_vm'] = 1;
                    Db::name('ims_meeting_join')->insert($join);
                }
            }

            // 添加挑战数据
            if ($id && isset($data['challenge_id']) && !isset($data['fight_id']) ) {
                $game['initiator_uid'] = $data_new['user_id'];
                $game['initiator_vm_id'] = $id;
                $game['party_uid'] = $data_new['challenge_id'];
                $game['create_time'] = date("Y-m-d H:i:s", time());
                Db::name('ims_straming_game')->insert($game);
            }
            // 更新挑战数据
            if ($id && isset($data['challenge_id']) && isset($data['fight_id']) ) {
                $game['party_vm_id'] = $id;
                $game['pk_status'] = 1;
                $game['update_time'] = date("Y-m-d H:i:s", time());
                Db::name('ims_straming_game')->where('initiator_vm_id', $data['fight_id'])->update($game);
            }

            return ['code'=>'1', 'msg'=>'添加成功'];
        }
    }

    /**
     * 培训详情
     * @param [array] $[where] [<查询条件>]
     * @return   [<array|string>]
     */
    public function stramingDateils($where=array())
    {
        $info = $this->alias('vm')
        ->join('__IMS_MEMBER__ im','vm.user_id = im.id', 'left')
        ->join('__IMS_ADDRESS__ area','vm.join_address_id = area.id', 'left')
        ->field('vm.id,vm.user_id,vm.vm_title,vm.cover_pic,vm.intro as vm_intro,vm.join_way,vm.start_time,vm.duration,im.staff_number,im.staff_name,im.staff_duty,im.staff_deptname,im.staff_pic,im.motto as staff_motto,area.province_id,area.city_id,area.area_id,area.address')
        ->where($where)->find()->toArray();

        if ( $info ) {
            if ($info['cover_pic'])  $info['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$info['cover_pic'])); // 处理图片
            if ($info['staff_pic'])  $info['staff_pic'] = cmf_get_image_url(str_replace("\\","/",$info['staff_pic'])); // 处理图片
            if ($info['province_id']) $info['province'] = Db::name('ims_regions')->where('region_id',$info['province_id'])->value('region_name');
            if ($info['city_id']) $info['city'] = Db::name('ims_regions')->where('region_id',$info['city_id'])->value('region_name');
            if ($info['area_id']) $info['area'] = Db::name('ims_regions')->where('region_id',$info['area_id'])->value('region_name');
            unset($info['province_id']);
            unset($info['city_id']);
            unset($info['area_id']);

            // 查询参会记录
            $joinLogModel = new ImsJoinLogModel();
            $info['join'] = $joinLogModel->joinLogShow(['vm_id'=>$info['id'], 'is_vm'=>1], $info['start_time'], $info['duration']);

            // 获取必须参加人员列表
            $confereeModel = new ImsMeetingJoinModel();
            $info['confereeList'] = $confereeModel->confereeList(['vm_id'=>$info['id'], 'is_vm'=>1]);

        }

        return $info;
    }

    /**
     * 培训直播
     * @param   [array] $[where] [<查询条件>]
     * @return   [<array>]
     */
    public function meetingLive($where=array())
    {
        $info = $this->alias('vm')
        ->join('__IMS_MEMBER__ im','vm.user_id = im.id', 'left')
        ->field('vm.id,vm.vm_title,vm.cover_pic,vm.intro,vm.store_link,im.staff_number,im.staff_name,im.staff_duty,im.staff_deptname,im.staff_pic,im.motto as staff_motto')
        ->where($where)->find()->toArray();

        $info['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$info['cover_pic'])); // 处理图片

        // 获取参加人员列表
        $joinLogModel = new  ImsJoinLogModel();
        $info['joinList'] = $joinLogModel->joinLogList(['vm_id'=>$info['id'], 'is_vm'=>1, 'join_way'=>2]);

        return $info;
    }

    /**
     * 培训直播回放
     * @param   [array] $[where] [<查询条件>]
     * @return   [<array>]
     */
    public function stramingLivePlayback($where=array())
    {
        $info = $this->alias('vm')
        ->join('__IMS_MEMBER__ im','vm.user_id = im.id', 'left')
        ->field('vm.id,vm.vm_title,vm.cover_pic,vm.start_time,vm.player_amount,vm.score_mean,vm.store_link,im.staff_number,im.staff_name,im.staff_duty,im.staff_deptname,im.staff_pic')
        ->where($where)->find()->toArray();
        if ($info['cover_pic']) $info['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$info['cover_pic'])); // 处理图片

        return $info;
    }

    /**
     * 培训列表
     * @param  [array] $[where] [<查询条件>]
     * @param  [int] $[page] [<分页>]
     * @param  [int] $[limit] [<显示数量>]
     * @param  [string] $[order] [<排序规则>]
     * @return   [<array>]
     */
    public function stramingList($where=array(), $page=1, $limit=5, $order='vm.id desc', $field='vm.id,vm.vm_title,vm.cover_pic,vm.share_amount,im.staff_duty,im.staff_name')
    {
        $list = $this->alias('vm')
        ->join('__IMS_MEMBER__ im','im.id = vm.user_id', 'left')
        ->field($field)
        ->where($where)->order($order)->page($page, $limit)->select()->toArray();
        foreach ( $list as $key => $val ) {
            $list[$key]['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$val['cover_pic'])); // 处理图片
        }

        $count = $this->alias('vm')
        ->join('__IMS_MEMBER__ im','im.id = vm.user_id', 'left')
        ->where($where)->count();

        return ['list'=>$list, 'count'=>$count];
    }

    /**
     * [stramingPkClassic 查询PK列表]
     * @param  array   $where [查询条件]
     * @param  integer $page  [分页的页码]
     * @param  integer $limit [每页查询的条数]
     * @param  string  $order [查询顺序]
     * @param  string  $field [查询字段]
     * @return [array]         [返回结果]
     */
    public function stramingPkClassic($where=[], $page=1, $limit=6, $order='player_amount desc;score_meandesc; id desc', $field="id,vm_title,start_time,cover_pic,player_amount,score_mean")
    {
        $list = $this->where($where)->whereNotNull('challenge_id')->field($field)->order($order)->page($page, $limit)->select()->toArray();
        foreach ( $list as $key => $val ) {
            $list[$key]['cover_pic'] = cmf_get_image_url(str_replace("\\","/",$val['cover_pic']));
            // 查询PK资讯
            $pkInfo = Db::name('ims_straming_game')->where('initiator_vm_id', $val['id'])->whereOR('party_vm_id', $val['id'])->field('initiator_uid,party_uid')->find();
            if ( $pkInfo ) {
                $pkInfo['initiator'] = Db::name('ims_member')->where('id', $pkInfo['initiator_uid'])->field('staff_number,staff_name,staff_duty,staff_deptname')->find(); // 发起者
                $pkInfo['party'] = Db::name('ims_member')->where('id', $pkInfo['party_uid'])->field('staff_number,staff_name,staff_duty,staff_deptname')->find(); // 被挑战者
            }
            $list[$key]['pkInfo'] = $pkInfo;
        }

        $count = $this->where($where)->whereNotNull('challenge_id')->count();

        return ['list'=>$list, 'count'=>$count];
    }
}